package cn.fuxi2022.auth.service.impl;


import cn.fuxi2022.auth.mapper.UserLoginMapper;
import cn.fuxi2022.auth.service.UserLoginService;
import cn.fuxi2022.core.exception.SmartGroupException;
import cn.fuxi2022.core.model.empty.auth.UserLogin;
import cn.fuxi2022.core.utils.JwtUtils;
import cn.fuxi2022.core.utils.PasswordUtils;
import cn.fuxi2022.core.utils.Query;
import cn.fuxi2022.model.resp.PageUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @author admin
 * @description 针对表【user_login(后端系统用户表)】的数据库操作Service实现
 * @createDate 2022-09-14 14:48:48
 */
@Service
public class UserLoginServiceImpl extends ServiceImpl<UserLoginMapper, UserLogin>
        implements UserLoginService {

    @Override
    public String login(String phone, String password) {

        // 构造手机号查询条件
        LambdaQueryWrapper<UserLogin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserLogin::getPhone, phone);

        UserLogin userLogin = this.getOne(wrapper);

        // 判断手机号对应的用户是否存在
        if (Objects.isNull(userLogin) || Objects.isNull(userLogin.getId())) {
            throw new SmartGroupException("手机号输入错误，请确认后再重新提交");
        }

        // 判断密码是否正确
        if (!PasswordUtils.checkPwd(password, userLogin.getPassword())) {
            throw new SmartGroupException("密码输入错误，请确认后再重新提交");
        }

        // 根据用户ID，生成token
        return JwtUtils.getJwtToken(userLogin.getId());
    }

    @Override
    public String loginByWeChat(String unionId) {
        // 根据用户ID，生成token
        return JwtUtils.getJwtToken(getUserByUnionId(unionId).getId());
    }

    @Override
    public void updateByWeChat(HashMap<String, String> userInfo) {
        // 1.获取 unionid
        String unionId = Optional.ofNullable(userInfo.get("unionid")).orElseThrow(
                () -> new SmartGroupException("获取不到unionid，非法的用户信息更新")
        );

        // 2.构造unionID查询条件
        UserLogin user = getUserByUnionId(unionId);

        // 3.根据微信更新用户信息
        Optional.ofNullable(userInfo.get("nickname")).ifPresent(user::setNickname);
        Optional.ofNullable(userInfo.get("sex")).ifPresent(sex -> user.setSex(Integer.valueOf(userInfo.get("sex"))));
        Optional.ofNullable(userInfo.get("headimgurl")).ifPresent(user::setAvatar);

        // 4.将更新后的对象插入数据库
        this.updateById(user);
    }

    @Override
    public void registerByWeChat(HashMap<String, String> userInfo) {
        // 1.创建用户对象
        UserLogin user = new UserLogin();

        // 2.根据微信更新用户信息
        Optional.ofNullable(userInfo.get("unionid")).ifPresent(user::setUnionId);
        Optional.ofNullable(userInfo.get("openid")).ifPresent(user::setOpenid);

        Optional.ofNullable(userInfo.get("nickname")).ifPresent(user::setNickname);
        Optional.ofNullable(userInfo.get("sex")).ifPresent(sex -> user.setSex(Integer.valueOf(userInfo.get("sex"))));
        Optional.ofNullable(userInfo.get("headimgurl")).ifPresent(user::setAvatar);

        // 3.保存用户
        this.save(user);
    }

    /**
     * 根据 unionId 查询用户
     *
     * @param unionId 微信开放平台的unionId
     * @return 查询到的用户
     */
    private UserLogin getUserByUnionId(String unionId) {
        LambdaQueryWrapper<UserLogin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserLogin::getUnionId, unionId);

        // 获取用户信息
        UserLogin userLogin = this.getOne(wrapper);

        // 判断用户是否存在，不存在说明用户响需要注册
        if (Objects.isNull(userLogin) || Objects.isNull(userLogin.getId())) {
            throw new SmartGroupException("该用户还未注册，请联系管理员注册后再登录");
        }
        // 判断用户登录是否完善
        if (StringUtils.isEmpty(userLogin.getPhone())) {
            throw new SmartGroupException("该用户注册未完善，请联系管理员完善注册");
        }
        return userLogin;
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        // 1.构建搜索条件
        LambdaQueryWrapper<UserLogin> wrapper = new LambdaQueryWrapper<>();
        // 按照创建日期排序
        wrapper.orderByDesc(UserLogin::getGmtCreate);
        
        // 3.工具分页
        IPage<UserLogin> page = this.page(
                new Query<UserLogin>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }
}




